<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>供应商管理系统</title>
    <meta name="description" content="这是一个 index 页面">
    <meta name="keywords" content="index">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="icon" type="image/png" href="assets/i/favicon.png">
    <link rel="apple-touch-icon-precomposed" href="assets/i/app-icon72x72@2x.png">
    <meta name="apple-mobile-web-app-title" content="Amaze UI"/>
    <link rel="stylesheet" href="assets/css/amazeui.min.css"/>
    <link rel="stylesheet" href="assets/css/admin.css">
    <link rel="stylesheet" href="assets/css/app.css">
</head>

<body data-type="generalComponents">
<header class="am-topbar am-topbar-inverse admin-header">
    <div class="am-collapse am-topbar-collapse" id="topbar-collapse">
        <ul class="am-nav am-nav-pills am-topbar-nav am-topbar-right admin-header-list tpl-header-list">
            <li class="am-dropdown" data-am-dropdown data-am-dropdown-toggle>
                <a class="am-dropdown-toggle tpl-header-list-link" href="javascript:;">
                    <span class="tpl-header-list-user-nick" id="currentUserName">暂无昵称</span><span class="tpl-header-list-user-ico"> <img
                        src="assets/img/user01.png"></span>
                </a>
                <ul class="am-dropdown-content">
                    <li><a href="login.html"><span class="am-icon-power-off"></span> 退出</a></li>
                </ul>
            </li>
        </ul>
    </div>
</header>
<div class="tpl-page-container tpl-page-header-fixed">
    <div class="tpl-left-nav tpl-left-nav-hover">
        <div class="tpl-left-nav-list">
            <ul class="tpl-left-nav-menu">
                <li class="tpl-left-nav-item">
                    <a href="javascript:;" class="nav-link tpl-left-nav-link-list">
                        <i class="am-icon-wpforms"></i>
                        <span>企业管理</span>
                        <i class="am-icon-angle-right tpl-left-nav-more-ico am-fr am-margin-right"></i>
                    </a>
                    <ul class="tpl-left-nav-sub-menu">
                        <li>
                            <a href="info-certification.html">
                                <i class="am-icon-angle-right"></i>
                                <span>企业信息认证</span>
                            </a>
                        </li>
                    </ul>
                </li>
                <li class="tpl-left-nav-item">
                    <a href="javascript:;" class="nav-link tpl-left-nav-link-list active">
                        <i class="am-icon-table"></i>
                        <span>供应商管理</span>
                        <i class="am-icon-angle-right tpl-left-nav-more-ico am-fr am-margin-right tpl-left-nav-more-ico-rotate"></i>
                    </a>
                    <ul class="tpl-left-nav-sub-menu" style="display:block">
                        <li>
                            <a href="white-list.html">
                                <i class="am-icon-angle-right"></i>
                                <span>供应商白名单</span>
                            </a>
                            <a href="black-list.html" class="active">
                                <i class="am-icon-angle-right"></i>
                                <span>供应商黑名单</span>
                            </a>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
    <div class="tpl-content-wrapper">
        <div class="tpl-content-page-title">
            供应商黑名单列表
        </div>
        <ol class="am-breadcrumb">
            <li class="am-active"><a style="color: #999999;">供应商管理</a></li>
            <li class="am-active">供应商黑名单</li>
        </ol>
        <div class="tpl-portlet-components">
            <div class="tpl-block">
                <div class="am-g">
                    <div class="am-u-sm-6 am-u-md-2">
                        <div class="am-input-group am-input-group-sm">
                                <span class="am-input-group-btn">
                                    <span style="font-size: 14px;margin-right: 8px;margin-left: 8px">企业名称</span>
                                </span>
                            <input type="text" id="searchSupplierName" class="am-form-field" placeholder="请输入企业名称"
                                   style="border: 1px solid #c2cad8;border-radius: 3px;">
                        </div>
                    </div>

                    <div style="float:right">
                        <div class="am-form-group">
                            <button type="button" class="am-btn am-btn-primary am-btn-sm"
                                    id="doc-prompt-toggle">添加供应商
                            </button>
                        </div>
                    </div>
                    <div class="am-modal am-modal-prompt" tabindex="-1" id="my-prompt">
                        <div class="am-modal-dialog">
                            <form action="" class="am-form am-form-horizontal">
                                <legend style="font-size: 18px;padding: 12px 0;">添加供应商到黑名单</legend>
                                <div class="am-form-group">
                                    <label for="addSupplierSelect" class="am-u-sm-4 am-form-label"
                                           style="font-size: 15px;">企业名称</label>
                                    <div class="am-u-sm-6">
                                        <select id="addSupplierSelect" required>
                                            <option value="">请选择企业</option>
                                        </select>
                                    </div>
                                    <span class="am-form-caret"></span>
                                </div>
                                <div class="am-form-group">
                                    <label class="am-u-sm-4 am-form-label"
                                           style="font-size: 15px;">统一社会信用代码</label>
                                    <div class="am-u-sm-6" style=" text-align: left;margin-top: 6px;">
                                        <span id="addSupplierCreditCode">请先选择企业</span>
                                    </div>
                                    <span class="am-form-caret"></span>
                                </div>
                                <div class="am-form-group" style="margin-bottom: 20px;">
                                    <label class="am-u-sm-4 am-form-label"
                                           style="font-size: 15px;">添加理由</label>
                                    <div class="am-u-sm-6">
                                        <textarea rows="4" id="addSupplierReason" placeholder="请输入添加理由" required></textarea>
                                    </div>
                                    <span class="am-form-caret"></span>
                                </div>
                            </form>
                            <div class="am-modal-footer" style="border-top: 1px solid #dedede;">
                                <span class="am-modal-btn" data-am-modal-cancel>取消</span>
                                <span class="am-modal-btn" data-am-modal-confirm>提交</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="am-g">
                    <div class="am-u-sm-12">
                        <form class="am-form">
                            <table class="am-table am-table-striped am-table-hover table-main">
                                <thead>
                                <tr>
                                    <th class="table-id">序号</th>
                                    <th class="table-title">企业名称</th>
                                    <th class="table-type">企业联系人</th>
                                    <th class="table-author am-hide-sm-only">联系方式</th>
                                    <th class="table-date am-hide-sm-only">联系邮箱</th>
                                    <th class="table-date am-hide-sm-only">添加理由</th>
                                    <th class="table-date am-hide-sm-only">更新日期</th>
                                    <th class="table-set">操作</th>
                                </tr>
                                </thead>
                                <tbody id="blackListTableBody">
                                    <!-- 动态加载的黑名单数据将在这里显示 -->
                                </tbody>
                            </table>
                            <div class="am-cf">

                                <div class="am-fr">
                                    <ul class="am-pagination tpl-pagination" id="pagination">
                                        <!-- 动态生成的分页将在这里显示 -->
                                    </ul>
                                </div>
                            </div>
                            <hr>
                        </form>
                    </div>
                </div>
            </div>
            <div class="tpl-alert"></div>
        </div>
    </div>
</div>

<!-- 解除黑名单确认模态框 -->
<div class="am-modal am-modal-confirm" tabindex="-1" id="removeFromBlackListModal">
    <div class="am-modal-dialog" style="font-size: 16px;">
        <div class="am-modal-hd">提示</div>
        <div class="am-modal-bd" id="removeConfirmMessage">
            将供应商解除黑名单后该企业可继续在平台进行融资，是否继续？
        </div>
        <div class="am-modal-footer">
            <span class="am-modal-btn" data-am-modal-cancel>取消</span>
            <span class="am-modal-btn" data-am-modal-confirm>确定</span>
        </div>
    </div>
</div>

<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/amazeui.min.js"></script>
<script src="assets/js/app.js"></script>
<script>
    let currentPage = 1;
    const pageSize = 5;
    let totalPages = 1;

    // 页面加载完成后执行
    $(document).ready(function() {
        loadCurrentUserInfo();
        loadBlackList(currentPage);
        loadAvailableSuppliers();
        
        // 搜索功能
        /*对 文本输入框（如 #searchSupplierName）：keyup 实现 “输入时实时搜索”，change 处理 “粘贴内容后点击其他地方” 的场景。
对 下拉选择框（如 #searchSupplierLevel）：change 会在选择选项后立即触发，keyup 基本无效（因为下拉框通常不用键盘输入）。*/
        $('#searchSupplierName, #searchSupplierLevel').on('change keyup', function() {
            currentPage = 1;
            loadBlackList(currentPage);
        });
    });

    // 加载当前用户信息
    function loadCurrentUserInfo() {
        $.get("/asd/login/getCurrentUser", function(result) {
            if (typeof result === 'string' && result.indexOf('未登录') > -1) {
                alert('用户未登录，请先登录');
                window.location.href = 'login.html';
                return;
            }

            if (typeof result === 'object' && result.account) {
                // 更新导航栏用户名显示
                if (result.name && result.name.trim() !== '') {
                    $('#currentUserName').text(result.name);
                } else {
                    $('#currentUserName').text('暂无昵称');
                }
            } else {
                $('#currentUserName').text('暂无昵称');
            }
        })
            .fail(function() {
                $('#currentUserName').text('暂无昵称');
                console.error('获取用户信息失败');
            });
    }

    // 加载黑名单数据
    function loadBlackList(page) {
        const supplierName = $('#searchSupplierName').val();
        const supplierLevel = $('#searchSupplierLevel').val();

        $.get("/asd/blacklist/getBlackList", {
            "page": page,
            "size": pageSize,
            "supplierName": supplierName,
            "supplierLevel": supplierLevel
        }, function(result) {
            console.log('黑名单数据响应:', result);

            if (result && result.content) {
                renderBlackListTable(result.content);
                renderPagination(result.totalPages, page);
                currentPage = page;
                totalPages = result.totalPages;
            } else {
                $('#blackListTableBody').html('<tr><td colspan="8" style="text-align: center;">暂无数据</td></tr>');
                $('#pagination').html('');
            }
        })
            .fail(function() {
                console.error('加载黑名单数据失败');
                $('#blackListTableBody').html('<tr><td colspan="8" style="text-align: center;">加载数据失败</td></tr>');
            });
    }

    // 渲染黑名单表格
    function renderBlackListTable(data) {
        let html = '';
        
        if (data && data.length > 0) {
            data.forEach(function(item, index) {
                const rowNumber = (currentPage - 1) * pageSize + index + 1;
                html += `
                    <tr data-supplier-id="${item.supplierId}">
                        <td>${rowNumber}</td>
                        <td><a href="#">${item.supplierName || '未知企业'}</a></td>
                        <td>${item.contactPerson || '未知'}</td>
                        <td class="am-hide-sm-only">${item.contactPhone || '未知'}</td>
                        <td class="am-hide-sm-only">${item.contactEmail || '未知'}</td>
                        <td class="am-hide-sm-only">
                            <div>${item.reason || '/'}</div>
                        </td>
                        <td class="am-hide-sm-only">${item.updateTime || '未知'}</td>
                        <td>
                            <div class="am-btn-toolbar">
                                <div class="am-btn-group am-btn-group-xs">
                                    <span class="am-text-secondary am-icon remove-from-blacklist" 
                                          style="cursor:pointer" 
                                          data-supplier-id="${item.supplierId}" 
                                          data-supplier-name="${item.supplierName}">
                                        <span></span>解除黑名单
                                    </span>
                                </div>
                            </div>
                        </td>
                    </tr>
                `;
            });
        } else {
            html = '<tr><td colspan="8" style="text-align: center;">暂无数据</td></tr>';
        }
        
        $('#blackListTableBody').html(html);
    }

    // 渲染分页
    function renderPagination(totalPages, currentPage) {
        if (totalPages <= 1) {
            $('#pagination').html('');
            return;
        }
        
        let html = '';
        
        // 上一页
        if (currentPage > 1) {
            html += `<li><a href="javascript:void(0)" onclick="loadBlackList(${currentPage - 1})">«</a></li>`;
        } else {
            html += '<li class="am-disabled"><a href="javascript:void(0)">«</a></li>';
        }
        
        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === currentPage) {
                html += `<li class="am-active"><a href="javascript:void(0)">${i}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadBlackList(${i})">${i}</a></li>`;
            }
        }
        
        // 下一页
        if (currentPage < totalPages) {
            html += `<li><a href="javascript:void(0)" onclick="loadBlackList(${currentPage + 1})">»</a></li>`;
        } else {
            html += '<li class="am-disabled"><a href="javascript:void(0)">»</a></li>';
        }
        
        $('#pagination').html(html);
    }

    // 加载可添加到黑名单的供应商（所有可用企业）
    function loadAvailableSuppliers() {
        $.get("/asd/blacklist/getAvailableEnterprises", function(result) {
            console.log('可用供应商响应:', result);

            try {
                // 检查响应是否已经是对象（jQuery自动解析）还是字符串
                const enterprises = typeof result === 'string' ? JSON.parse(result) : result;

                let options = '<option value="">请选择企业</option>';
                if (enterprises && enterprises.length > 0) {
                    enterprises.forEach(enterprise => {
                        options += `<option value="${enterprise.id}" data-credit-code="${enterprise.creditCode || '未知'}">${enterprise.name}</option>`;
                    });
                }
                $('#addSupplierSelect').html(options);
            } catch (e) {
                console.error('解析企业数据失败:', e);
                console.log('原始响应:', result);
                $('#addSupplierSelect').html('<option value="">解析数据失败</option>');
            }
        })
            .fail(function() {
                console.error('加载可用供应商失败');
                $('#addSupplierSelect').html('<option value="">加载失败</option>');
            });
    }

    // 企业选择变化时更新统一社会信用代码
    $('#addSupplierSelect').on('change', function() {
        const selectedOption = $(this).find('option:selected');
        const creditCode = selectedOption.data('credit-code') || '请先选择企业';
        $('#addSupplierCreditCode').text(creditCode);
    });

    // 解除黑名单
    function removeFromBlackList(supplierId, supplierName) {
        $('#removeConfirmMessage').html(`将供应商解除黑名单后该企业可继续在平台进行融资 <br> 确定要将 ${supplierName} 从黑名单中移除吗？`);

        $('#removeFromBlackListModal').modal({
            onConfirm: function() {
                $.post("/asd/blacklist/removeFromBlackList",{"supplierId": supplierId},
                    function(response) {
                        console.log('解除黑名单响应:', response);
                        console.log('响应类型:', typeof response);

                        let message = '';

                        // 处理不同类型的响应
                        if (typeof response === 'string') {
                            message = response;
                        } else if (response && response.message) {
                            message = response.message;
                        } else {
                            message = '解除成功';
                        }

                        alert(message);

                        // 无论响应格式如何，都刷新列表
                        loadBlackList(currentPage);
                        loadAvailableSuppliers(); // 刷新可用供应商列表
                    })
                    .fail(function() {
                        alert('网络请求失败');

                });
            },
            onCancel: function() {
                console.log('取消解除黑名单');
            }
        });
    }

    // 绑定解除黑名单事件
    $(document).on('click', '.remove-from-blacklist', function() {
        const supplierId = $(this).data('supplier-id');
        const supplierName = $(this).data('supplier-name');
        removeFromBlackList(supplierId, supplierName);
    });

    // 添加供应商到黑名单
    $('#doc-prompt-toggle').on('click', function() {
        loadAvailableSuppliers(); // 每次打开弹窗时重新加载可用企业
            $('#my-prompt').modal({
                relatedTarget: this,
            onConfirm: function() {
                const supplierId = $('#addSupplierSelect').val();
                const reason = $('#addSupplierReason').val().trim();

                if (!supplierId) {
                    alert('请选择企业');
                    return;
                }

                if (!reason) {
                    alert('请输入添加理由');
                    return;
                }

                // 改造后的“添加到黑名单”请求（替换原 $.ajax 代码）
                $.get('/asd/blacklist/addToBlackList',
                    // 请求参数：与原 ajax 的 data 一致（供应商ID、添加理由）
                    {
                        supplierId: supplierId,
                        reason: reason
                    },
                    // 成功回调函数：与原 ajax 的 success 逻辑对齐，增加 try-catch 异常捕获
                    function(response) {
                        try {
                            console.log('添加到黑名单响应:', response);
                            console.log('响应类型:', typeof response);

                            // 处理响应数据：兼容后端返回字符串或JSON对象（与加载白名单逻辑一致）
                            const result = typeof response === 'string' ? JSON.parse(response) : response;
                            let message = '';

                            // 响应消息判断：优先取后端自定义消息，无则用默认提示
                            if (typeof response === 'string') {
                                message = response; // 后端直接返回字符串（如“添加成功”“参数错误”）
                            } else if (result && result.message) {
                                message = result.message; // 后端返回JSON对象，包含message字段
                            } else {
                                message = '添加成功'; // 默认成功提示（兜底逻辑）
                            }

                            // 提示用户操作结果
                            alert(message);

                            // 业务逻辑：刷新列表+重置表单（与原代码完全一致）
                            loadBlackList(currentPage); // 刷新黑名单列表（保持当前页码）
                            loadAvailableSuppliers();   // 刷新可用供应商列表（用于添加弹窗下拉框）

                            // 重置添加弹窗表单（避免下次打开残留旧数据）
                            $('#addSupplierSelect').val('');
                            $('#addSupplierReason').val('');
                            $('#addSupplierCreditCode').text('请先选择企业');
                        } catch (e) {
                            // 捕获JSON解析异常或代码执行异常（与加载白名单的异常处理逻辑一致）
                            console.error('解析添加黑名单响应失败:', e);
                            alert('数据格式错误'); // 给用户明确的错误提示
                        }
                    }
                )
                    // 请求失败回调：与加载白名单的 fail 逻辑完全一致（网络错误、后端500等）
                    .fail(function() {
                        alert('网络请求失败');
                    });
            },
            onCancel: function() {
                // 重置表单
                $('#addSupplierSelect').val('');
                $('#addSupplierReason').val('');
                $('#addSupplierCreditCode').text('请先选择企业');
            }
        });
    });
</script>
</body>

</html>